/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package multiface.valentinorusso.servlet;

import it.sauronsoftware.base64.Base64;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.AbstractList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import multiface.valentinorusso.jpa.*;
import multiface.valentinorusso.jpa.util.*;
import multiface.web.util.Util;
import multiface.web.util.categories.AlberoCategorie;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author Diego64
 */
@WebServlet(name = "ActionServlet", urlPatterns = {"/ActionServlet"})
public class ActionServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    private static org.apache.commons.logging.Log log = LogFactory.getLog(ActionServlet.class);

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        //Write LogDB
        Util.logDB(request);
        //

        try {
            HttpSession s = request.getSession();
            String adm = request.getParameter("adm");

            if (s.getAttribute("admin") != null && adm.equals(s.getId())) {
                String action = request.getParameter("action");

                EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
                EntityManager em = emf.createEntityManager();

                Date d = new Date();


                //OPZIONI
                if (action.equalsIgnoreCase("mod_opzioni")) {
                    String oid = request.getParameter("oid");
                    String tipo = request.getParameter("tipo");

                    String email_contatto = request.getParameter("email_contatto");
                    String smtp_host = request.getParameter("smtp_host");
                    String smtp_user = request.getParameter("smtp_user");
                    String smtp_password = request.getParameter("smtp_password");
                    String max_record_page = request.getParameter("max_record_page");
                    String max_record_page_admin = request.getParameter("max_record_page_admin");
                    String max_pag_paginator = request.getParameter("max_pag_paginator");

                    Opzioni u = em.find(Opzioni.class, Integer.parseInt(oid));
                    u.setEmailContatto(email_contatto);
                    u.setMaxRecordPag(Integer.parseInt(max_record_page));
                    u.setMaxRecordPagAdmin(Integer.parseInt(max_record_page_admin));
                    u.setSmtpHost(smtp_host);
                    u.setSmtpPassword(Base64.encode(smtp_password));
                    u.setSmtpUser(smtp_user);
                    u.setMaxPagPaginator(Integer.parseInt(max_pag_paginator));


                    em.getTransaction().begin();
                    em.persist(u);
                    em.getTransaction().commit();
                }

                //UTENTE
                if (action.equalsIgnoreCase("add_utente")) {
                    String uid = request.getParameter("uid");
                    String tipo = request.getParameter("tipo");
                    String nome = request.getParameter("nome");
                    String cognome = request.getParameter("cognome");
                    String user = request.getParameter("user");
                    String newpsw = request.getParameter("newpsw");

                    Utente u = new Utente();
                    u.setNome(nome);
                    u.setCognome(cognome);
                    u.setTipo(tipo);
                    u.setUsername(user);
                    if (newpsw != null && !newpsw.equals("")) {
                        u.setPassword(Base64.encode(newpsw));
                    }

                    em.getTransaction().begin();
                    em.persist(u);
                    em.getTransaction().commit();
                }

                if (action.equalsIgnoreCase("mod_utente")) {
                    String uid = request.getParameter("uid");
                    String tipo = request.getParameter("tipo");
                    String nome = request.getParameter("nome");
                    String cognome = request.getParameter("cognome");
                    String user = request.getParameter("user");
                    String newpsw = request.getParameter("newpsw");

                    Utente u = em.find(Utente.class, Integer.parseInt(uid));
                    u.setNome(nome);
                    u.setCognome(cognome);
                    u.setTipo(tipo);
                    u.setUsername(user);
                    if (newpsw != null && !newpsw.equals("")) {
                        u.setPassword(Base64.encode(newpsw));
                    }

                    em.getTransaction().begin();
                    em.persist(u);
                    em.getTransaction().commit();
                }



                // LAVORI
                if (action.equalsIgnoreCase("add_lavoro")) {
                    String nome = request.getParameter("nome");
                    String descrizione = request.getParameter("descrizione");
                    String cid = request.getParameter("cid");

                    Lavoro l = new Lavoro();
                    l.setCategoria(em.find(Categoria.class, Integer.parseInt(cid)));
                    l.setDataora(new Timestamp(d.getTime()));
                    l.setNome(nome);
                    l.setDescrizione(descrizione);

                    em.getTransaction().begin();
                    em.persist(l);
                    em.getTransaction().commit();
                }



                if (action.equalsIgnoreCase("add_cat")) {
                    String nome = request.getParameter("nome");
                    String descrizione = request.getParameter("descrizione");

                    Categoria c = new Categoria();
                    c.setNome(nome);
                    c.setDescrizione(descrizione);
                    c.setOrdine(1);
                    c.setSopracategoria(-1);

                    Query q = em.createNativeQuery("SELECT MAX(ordine) FROM categoria WHERE sopracategoria=?");
                    q.setParameter(1, c.getSopracategoria());
                    Object res = q.getSingleResult();
                    if (res != null) {
                        c.setOrdine(Integer.parseInt(res.toString()) + 1);
                    } else {
                        c.setOrdine(0);
                    }

                    em.getTransaction().begin();
                    em.persist(c);
                    em.getTransaction().commit();

                }
                if (action.equalsIgnoreCase("mod_cat")) {
                    String nome = request.getParameter("nome");
                    String descrizione = request.getParameter("descrizione");
                    String tipo = request.getParameter("tipo");

                    Categoria c = em.find(Categoria.class, Integer.parseInt(request.getParameter("cid")));
                    c.setNome(nome);
                    c.setDescrizione(descrizione);
                    em.getTransaction().begin();
                    em.persist(c);
                    em.getTransaction().commit();
                }

                if (action.equalsIgnoreCase("move_cat")) {
                    String move = request.getParameter("move");
                    String cid = request.getParameter("cid");


                    if (move.equalsIgnoreCase("up")) {
                        Categoria c = em.find(Categoria.class, Integer.parseInt(cid));
                        Categoria c_up = em.createNamedQuery("Categoria.findByOrdine", Categoria.class).setParameter("ordine", c.getOrdine() - 1).getSingleResult();

                        c.setOrdine(c.getOrdine() - 1);
                        c_up.setOrdine(c_up.getOrdine() + 1);

                        em.getTransaction().begin();
                        em.persist(c);
                        em.persist(c_up);
                        em.getTransaction().commit();
                    }

                    if (move.equalsIgnoreCase("down")) {
                        Categoria c = em.find(Categoria.class, Integer.parseInt(cid));
                        Categoria c2 = em.createNamedQuery("Categoria.findByOrdine", Categoria.class).setParameter("ordine", c.getOrdine() + 1).getSingleResult();

                        c.setOrdine(c.getOrdine() + 1);
                        c2.setOrdine(c2.getOrdine() - 1);

                        em.getTransaction().begin();
                        em.persist(c);
                        em.persist(c2);
                        em.getTransaction().commit();
                    }



                }

                if (action.equalsIgnoreCase("mod_lavoro")) {
                    String nome = request.getParameter("nome");
                    String descrizione = request.getParameter("descrizione");
                    String tipo = request.getParameter("tipo");
                    String anno = request.getParameter("anno");
                    String mq = request.getParameter("mq");
                    String luogo = request.getParameter("luogo");
                    String lid = request.getParameter("lid");
                    String cid = request.getParameter("cid");

                    Lavoro l = em.find(Lavoro.class, Integer.parseInt(lid));
                    l.setCategoria(em.find(Categoria.class, Integer.parseInt(cid)));
                    l.setDataora(new Timestamp(d.getTime()));
                    l.setDescrizione(descrizione);

                    l.setNome(nome);

                    em.getTransaction().begin();
                    em.persist(l);
                    em.getTransaction().commit();
                }

                if (action.equalsIgnoreCase("cover_file")) {
                    Lavoro p = em.find(Lavoro.class, Integer.parseInt(request.getParameter("lid")));
                    em.refresh(p);
                    List<File> lf = p.getFileList();

                    em.getTransaction().begin();
                    for (File f : lf) {
                        f.setCopertina(false);
                        if (f.getIdfile() == Integer.parseInt(request.getParameter("fid"))) {
                            f.setCopertina(true);
                        }
                        em.persist(f);
                    }
                    em.getTransaction().commit();
                }


                if (action.equalsIgnoreCase("del_cat")) {
                    Categoria c = em.find(Categoria.class, Integer.parseInt(request.getParameter("cid")));
                    em.getTransaction().begin();
                    em.remove(c);
                    em.getTransaction().commit();
                }
                if (action.equalsIgnoreCase("del_file")) {
                    File c = em.find(File.class, Integer.parseInt(request.getParameter("fid")));
                    em.getTransaction().begin();
                    em.remove(c);
                    em.getTransaction().commit();
                }
                if (action.equalsIgnoreCase("del_lavoro")) {
                    Lavoro c = em.find(Lavoro.class, Integer.parseInt(request.getParameter("lid")));
                    em.getTransaction().begin();
                    em.remove(c);
                    em.getTransaction().commit();
                }
                if (action.equalsIgnoreCase("del_utente")) {
                    Utente c = em.find(Utente.class, Integer.parseInt(request.getParameter("uid")));
                    if (em.createNativeQuery("SELECT * from utente", Utente.class).getResultList().size() > 1) {
                        em.getTransaction().begin();
                        em.remove(c);
                        em.getTransaction().commit();
                    } else {

                        out.print(org.apache.commons.lang3.StringEscapeUtils.escapeHtml4(Base64.encode("Non è possibile eliminare l'ultimo utente.")));
                    }
                }
                em.close();
            } else {
            }
        } catch (Exception ex) {
            out.print(ex.toString());
            //out.print(Base64.encode(ex.toString()));
            Util.logDB(request, ex);
            log.error(ex);
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
